<?php
/*
 * @FilePath: \crm\application\crm\model\auth\AuthNode.php
 */

namespace app\crm\model\auth;

use app\crm\model\auth\Role;
use think\Model;
use think\facade\Session;

class AuthNode extends Model
{
    protected $autoWriteTimestamp = true;

    protected function checked($val, $children)
    {
        $admin = session('admin');
        $NodeList = explode(',', Role::where('id', $admin['role_id'])->find()['node_id']);
        $checked = (array_search($val, $NodeList) !== false && empty($children)) ? true : '';
        return $checked;
    }

    public function AuthNodeList()
    {
        $Node = $this->where('parent_id', 0)->field('id,title')->all();
        foreach ($Node as $val1) {
            $val1['spread'] = true;
            $children = [];  
            $Node2 = $this->where('parent_id', $val1['id'])->field('id,title')->all();
            foreach ($Node2 as $val2) {
                $children2 = [];
                $Node3 = $this->where('parent_id', $val2['id'])->field('id,title')->all();
                foreach ($Node3 as $val3) {
                    $children3 = [];
                    $Node4 = $this->where('parent_id', $val3['id'])->field('id,title')->all();
                    foreach ($Node4 as $val4) {
                        $children3[] = ['spread' => true, 'id' => $val4['id'], 'title' => $val4['title'], 'checked' => $this->checked($val4['id'], [])];
                    }
                    $children2[] = ['spread' => true, 'id' => $val3['id'], 'title' => $val3['title'], 'children' => $children3, 'checked' => $this->checked($val3['id'], $children3)];
                }
                $children[] = ['spread' => true, 'id' => $val2['id'], 'title' => $val2['title'], 'children' => $children2];
            }
            $val1['children'] = $children;
            $list[] = $val1;
        }
        return $list;
    }
}
